<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Model\Message;
use DB,Session;

class MessageController extends CommonController
{
    // 获取所有未删除的消息
    public function index()
    {
        $messageList = Message::getUserMessage();
        
        return view('home.user.message', compact('messageList'));
    }
    
    // 查看消息
    public function show($id)
    {
        // 获取消息表里对应的数据
        $data = Message::where('id', $id)->first();
        
        if($data){
            // 修改阅读状态表的数据
            $user_id = Session::get('userData')->id;
            // 获取当前数据
            $read = DB::table('message_read')->where('user_id', $user_id)
                    ->where('msg_id', $id)
                    ->first();
            if($read->is_read != 1){
                $d['read_time'] = date('Y-m-d H:i:s');
                $d['is_read'] = 1;
                DB::table('message_read')->where('id', $read->id)->update($d);
            }
            return response()->json(['status'=>1,'info'=>$data]);
        } else {
            return response()->json(['status'=>1,'info'=>'消息未找到']);
        }
    }
    
    // 删除消息
    public function delete($id)
    {
        $res = DB::table('message_read')->where('id', $id)->delete();
        if(false !==  $res){
            return response()->json(['status'=>1,'info'=>'删除成功']);
        } else {
            return response()->json(['status'=>0,'info'=>'删除失败']);
        }
    }
    
    // 全社已读
    public function readall()
    {
        $userid = Session::get('userData')->id;
        DB::table('message_read')->where('user_id', $userid)
            ->where('is_read', 0)
            ->update(['is_read'=>1, 'read_time'=>date('Y-m-d H:i:s')]);
        return back();
    }
    
    // 全部删除
    public function deleteall()
    {
        $userid = Session::get('userData')->id;
        DB::table('message_read')->where('user_id', $userid)->delete();
        return back();
    }
}
